package com.eatme.web.sys.quartz.service.impl;

import com.eatme.web.app.article.job.PublishArticleJob;
import com.eatme.web.sys.quartz.service.IScheduleService;
import org.apache.http.client.utils.DateUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.Month;
import java.util.Date;
import java.util.UUID;

@Service
public class ScheduleServiceImpl implements IScheduleService {
    private static final Logger LOG = LoggerFactory.getLogger(ScheduleServiceImpl.class);
    private String defaultGroup = "default";

    @Autowired
    private Scheduler scheduler;
    @Override
    public String scheduleJob(Class<? extends Job> jobBeanClass, String cron, Integer data) {
        String jobName = UUID.randomUUID().toString();
        //String jobName = UUID.fastUUID().toString();
        JobBuilder jobBuilder = JobBuilder.newJob(jobBeanClass);
        jobBuilder.withIdentity(jobName, defaultGroup);
        jobBuilder.usingJobData("data", data);
        JobDetail jobDetail = jobBuilder
                .build();
        //创建触发器，指定任务执行时间
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName, defaultGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .build();
        // 调度器进行任务调度
        try {
            scheduler.scheduleJob(jobDetail, cronTrigger);
        } catch (SchedulerException e) {
            LOG.error("任务调度执行失败{}", e.getMessage());
        }
        return jobName;
    }

    @Override
    public String scheduleFixTimeJob(Class<? extends Job> jobBeanClass, LocalDateTime publish_time, Integer data) {
        //日期转CRON表达式
        int year = publish_time.getYear();
        Month month = publish_time.getMonth();
        int day = publish_time.getDayOfMonth();
        int hour = publish_time.getHour();
        int minute = publish_time.getMinute();
        int second = publish_time.getSecond();
        LOG.info("今天是" + publish_time + "\n"
                + "年 ： " + year + "\n"
                + "月 ： " + month.getValue() + "-即 "+ month + "\n"
                + "日 ： " + day + "\n"
                + "时 ： " + hour + "\n"
                + "分 ： " + minute + "\n"
                + "秒 ： " + second + "\n"
        );
        String startCron = String.format("%d %d %d %d %d ? %d",
                year,
                month.getValue(),
                day,
                hour,
                minute,
                second
        );
        return scheduleJob(jobBeanClass, startCron, data);
    }

    @Override
    public Boolean cancelScheduleJob(String jobName) {
        boolean success = false;
        try {
            // 暂停触发器
            scheduler.pauseTrigger(new TriggerKey(jobName, defaultGroup));
            // 移除触发器中的任务
            scheduler.unscheduleJob(new TriggerKey(jobName, defaultGroup));
            // 删除任务
            scheduler.deleteJob(new JobKey(jobName, defaultGroup));
            success = true;
        } catch (SchedulerException e) {
            LOG.error("任务取消失败{}", e.getMessage());
        }
        return success;
    }
}
